package gac.helloworld;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.Calendar;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONTokener;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MapHandlerActivity {

	private Location currentLocation;
	private static double currLat;
	private static double currLng; 
	private int timeToDestination;
	private String finalDestination;
	private int endTime, bufferTime;
	private LocationManager lm;
	boolean gps_enabled=false;
	boolean network_enabled=false;
	private static Activity activity;
	private static int alarmCount = 0;
	private static LocationListener locationListener;

	public MapHandlerActivity(Activity a){
		activity = a;
		finalDestination = "";
		endTime = 0;
		bufferTime = 0;
		alarmCount++;

	}

	public static void findCurrentLocation(){
		// Acquire a reference to the system Location Manager
		if(locationListener==null){
			LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
			// Define a listener that responds to location updates
			locationListener = new LocationListener() {
				public void onLocationChanged(Location location) {
					Log.v("", "Latitude = "+location.getLatitude());
					Log.v("", "Longitude = "+location.getLongitude());
					currLat = location.getLatitude();
					currLng = location.getLongitude();
			}

				public void onStatusChanged(String provider, int status, Bundle extras) {}

				public void onProviderEnabled(String provider) {}

				public void onProviderDisabled(String provider) {}
			};

			// Register the listener with the Location Manager to receive location updates
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
		}
	}
	//To be used when timeToDestination was just calculated
	public int getTimeToDestination() {
		return timeToDestination;
	}

	public int calculateTime() {
		Log.v("","Time start");
		Log.v("","Lat = "+currLat+"\n     Long = "+currLng+ "\n   Time to destination: " + timeToDestination);
		String urlString = "http://maps.googleapis.com/maps/api/directions/json?origin="
			+ currLat
			+ ","
			+ currLng
			+ "&destination="
			+ finalDestination
			+ "&sensor=true";
		String result = "";
		try {
			
			URI mapURL = new URI(urlString);
			HttpClient hc = new DefaultHttpClient();
			HttpGet get = new HttpGet(mapURL);
			HttpResponse rp = hc.execute(get);
			if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(rp.getEntity());
			}
			//JSONTokener jtok = new JSONTokener(result);
			
			
			if(result.length() > 1000){
				
				result = result.substring(0,1000);
				String[] values = result.split("\"value\" : ");
				Scanner scan = new Scanner(values[2]);
				timeToDestination = scan.nextInt();
				//timeToDestination = Integer.parseInt(values[2]);
				Log.v("Time to destination","Time To destination "+ timeToDestination);
				//Toast.makeText(activity, ""+timeToDestination, Toast.LENGTH_LONG).show();
			}
			else{
				Log.v("URL", urlString);
				Log.v("result", result);
				
			}
			Log.v("Time to destination","Time To destination "+ timeToDestination);
			//System.out.println(currentTime);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Log.v("Time to destination", "Time to Destination"+timeToDestination);
		return timeToDestination;
	}

	public void setFinalDestination(String fd) {
		try {
			finalDestination = URLEncoder.encode(fd, "UTF-8");
			Log.v("Final Destination", finalDestination);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String getFinalDestination(){
		return finalDestination;
	}
	public void setEndTime(int e){
		endTime = e;
	}
	public void setBufferTime(int b){
		bufferTime = b;
	}
	//everything is in seconds
	public int getLeaveTimeInterval(){
		Calendar c = Calendar.getInstance();
		String sDate = c.get(Calendar.YEAR) + "-" 
		+ c.get(Calendar.MONTH)
		+ "-" + c.get(Calendar.DAY_OF_MONTH) 
		+ " at " + c.get(Calendar.HOUR_OF_DAY) 
		+ ":" + c.get(Calendar.MINUTE);
		int currTime = c.get(Calendar.HOUR_OF_DAY)*60*60+c.get(Calendar.MINUTE)*60;		
		calculateTime();
		int difference = endTime - bufferTime - timeToDestination - currTime;
		Log.w("Time info", "End Time " + endTime+ "\nbufferTime "+bufferTime+"\ntimeToDestination "+timeToDestination+"\ncurrTime"+currTime+"\nCurrent Time "+c.get(Calendar.HOUR_OF_DAY) + ":"+ c.get(Calendar.MINUTE));
		Log.w("Time interval difference (should be greater than 0", ""+difference);
		return difference;
	}
	public boolean isTimeToLeave(){
		return getLeaveTimeInterval()<=0;
	}
	public String timeUntilAlarm(){
		//return "something";
		/*
		MapHandlerActivity m = new MapHandlerActivity(activity);
		if(m.isTimeToLeave())
			return "0 minutes.";
		//m.setBufferTime(bT);
		//m.setEndTime(endT);
		m.setFinalDestination(fd);
		int currTime = Calendar.HOUR_OF_DAY*60*60+Calendar.MINUTE*60+Calendar.SECOND;
		m.calculateTime();
		int startTime = endT-m.timeToDestination-buffT;
		String time = "";
		int displayTime = (startTime-currTime);
		if(displayTime<0){
			displayTime+=24*60*60;
		}
		displayTime -=m.timeToDestination; 
		if(displayTime/(3600)>0){
			time += ""+displayTime/(3600)+" hours and ";
			displayTime-= (displayTime/3600)*3600;

		}
		time+=""+displayTime/60+" minutes.";
		Log.v("MapHandlerActivity/timeUntilAlarm","time: " + time);
		*/
		
		int deltaTime = getLeaveTimeInterval();
		String time = "";
		if(deltaTime<=0){
			return "You should leave now.";
		}
		if(deltaTime>3600){
			time+=""+ deltaTime/3600 +" hours and ";
			deltaTime%=3600;			
		}
		time += ""+deltaTime/60+" minutes.";
		Log.v("MapHandlerActivity/timeUntilAlarm","time: " + time);
		return time;
	}
	public static String timeUntilAlarm(String fd, int endT, int wT){
		MapHandlerActivity m = new MapHandlerActivity(activity);
		m.setBufferTime(wT);
		m.setEndTime(endT);
		m.setFinalDestination(fd);
		int deltaTime = m.getLeaveTimeInterval();
		String time = "";
		if(deltaTime<=0){
			return "You should leave now.";
		}
		if(deltaTime>3600){
			time+=""+ deltaTime/3600 +" hours and ";
			deltaTime%=3600;			
		}
		time += ""+deltaTime/60+" minutes.";
		Log.v("MapHandlerActivity/timeUntilAlarm","time: " + time);
		return time;
		
		
		
	}
}

